package com.fast.common.web.advice;


import com.fast.common.em.ResultEm;
import com.fast.common.pojo.resp.Result;
import com.fast.common.web.exception.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {


    /**
     * 全局异常.
     */
    @ExceptionHandler(Exception.class)
    public Result handleGlobalException(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return Result.error(ResultEm.ERROR, e.getMessage());
    }

    /**
     * 404.
     */
    @ExceptionHandler(ResponseStatusException.class)
    public Result handleGlobalException(ResponseStatusException e) {
        log.error("404资源未找到 ex={}", e.getMessage(), e);
        return Result.error(ResultEm.Not_RESOURCE);
    }

    /**
     * 断言 走无效参数code
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleGlobalException(IllegalArgumentException e) {
        log.error("400无效参数 ex={}", e.getMessage(), e);
        return Result.error(ResultEm.UN_PARAM, StringUtils.isBlank(e.getMessage()) ? ResultEm.UN_PARAM.message : e.getMessage());
    }
    /**
     * 缺少参数
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleGlobalException(HttpMessageNotReadableException e) {
        log.error("400无效参数 ex={}", e.getMessage(), e);
        return Result.error(ResultEm.UN_PARAM);
    }

    /**
     * 认证异常
     */
    @ExceptionHandler(AuthException.class)
    public Result handleGlobalException(AuthException e) {
        log.error("全局认证异常 ex={}", e.getMessage(), e);
        return Result.error(ResultEm.UN_AUTHORIZED, e.getMessage());
    }


}
